package com.xm.xmapp.fragment;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.android.volley.VolleyError;
import com.xm.xmapp.MainActivity;
import com.xm.xmapp.R;
import com.xm.xmapp.ShortTimeOrderPayActivity;
import com.xm.xmapp.app.CodeConstant;
import com.xm.xmapp.app.MyAppcation;
import com.xm.xmapp.app.RequestInterFaceCode.SeekCarCode;
import com.xm.xmapp.app.Type;
import com.xm.xmapp.app.Type.F_ShortTimeRentcar;
import com.xm.xmapp.base.BaseFragment;
import com.xm.xmapp.dialog.SongChePhoneTipDialog;
import com.xm.xmapp.myinterface.DisssmissInterFace;
import com.xm.xmapp.myinterface.GetDataInterFace;
import com.xm.xmapp.myinterface.MainActivityInterFace;
import com.xm.xmapp.myinterface.ScrollInterFaceAble;
import com.xm.xmapp.request.bean.Get_car_statusRequest;
import com.xm.xmapp.request.bean.Get_user_order_moneyRequest;
import com.xm.xmapp.request.bean.Handle_car_doorRequest;
import com.xm.xmapp.request.bean.Seek_carRequest;
import com.xm.xmapp.request.bean.Seek_carResponse;
import com.xm.xmapp.response.bean.BaseBeanResponse;
import com.xm.xmapp.response.bean.CustomHeightBean;
import com.xm.xmapp.response.bean.ResponseAppUserOrder;
import com.xm.xmapp.response.bean.ResponseCarStatus;
import com.xm.xmapp.response.bean.ResponseUserOrderMoney;
import com.xm.xmapp.response.bean.UserOrderInfoInterFace;
import com.xm.xmapp.tools.TimeUtil;
import com.xm.xmapp.tools.TimeUtil.TimeListener;
import com.xm.xmapp.tools.Tools;

import static com.xm.xmapp.R.id.close;
import static com.xm.xmapp.R.id.dianliangImg;
import static com.xm.xmapp.R.id.ll_btn;
import static com.xm.xmapp.R.id.open;
import static com.xm.xmapp.R.id.pay;
import static com.xm.xmapp.R.id.rl_close_car;
import static com.xm.xmapp.R.id.rl_find_car;
import static com.xm.xmapp.R.id.statusImg;
import static com.xm.xmapp.R.id.text3;
import static com.xm.xmapp.R.id.yuding;


public class ShortTimeRentcarFragment extends BaseFragment implements OnClickListener,ScrollInterFaceAble {


    /**
     * 定时任务，每个一段时间获取订单金额
     */

    TimeUtil task = new TimeUtil(2 * MyAppcation.getMyAppcation().get_money_second * 1000,
            MyAppcation.getMyAppcation().get_money_second * 1000);
    ImageView phone;
    TextView tvCarNumber;
    TextView tvCarGenreName;
    TextView tvCarSeat;
    TextView tvEndurance;
    TextView tvPay;
    TextView tvFinishUsing;
    RelativeLayout rlFindCar;
    RelativeLayout rlCloseCar;
    RelativeLayout rlOpenCar;
    LinearLayout layout,llEndurance,bottom;
    private ResponseAppUserOrder bean;
    /**
     * type = 1表示可以请求接口，打开车门 type = 0表示车门已开，可以关闭车门 默认是1
     */
    private int type = 1;
    private boolean isCancel = false;
    private boolean isOperateCar = true;
    private boolean isSearch = true;
    private Rect mRect;
    public ShortTimeRentcarFragment() {
        super();
    }

    /**
     * 已经有预约
     */
    public ShortTimeRentcarFragment(UserOrderInfoInterFace bean) {
        this.bean = (ResponseAppUserOrder) bean;
    }

    public void setBean(UserOrderInfoInterFace bean) {
        this.bean = (ResponseAppUserOrder) bean;
        if (view != null) {
            initData();
            initEvent();
        } else {
            task.cancel();
        }
    }

    @Override
    public int setContentView() {
        return R.layout.fragment_shorttime_order;
    }

    @Override
    public void onPause() {
        super.onPause();
        task.cancel();
    }

    /**
     * 0还车页面和后台还车，极光推送后，mainactivity调用，关掉定时器
     */
    @Override
    public Object dataChang(int flag, Object data) {

        switch (flag) {
            case F_ShortTimeRentcar.DEFAULT:
                isCancel = true;
                task.cancel();
                break;
            default:
                break;
        }
        return super.dataChang(flag, data);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        task.cancel();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (MyAppcation.getMyAppcation().getUserBean() != null && !isCancel)
            task.start();
    }

    @Override
    public void initView() {

        phone = (ImageView) findViewById(R.id.phone);
        layout = (LinearLayout) findViewById(R.id.layout);
        tvCarNumber = (TextView) findViewById(R.id.tv_car_number);
        tvPay = (TextView) findViewById(R.id.tv_pay);
        tvEndurance = (TextView) findViewById(R.id.tv_endurance);
        rlFindCar = (RelativeLayout) findViewById(R.id.rl_find_car);
        tvCarGenreName = (TextView) findViewById(R.id.tv_car_genre_name);
        tvCarSeat = (TextView) findViewById(R.id.tv_car_seat);
        rlCloseCar = (RelativeLayout) findViewById(R.id.rl_close_car);
        rlOpenCar = (RelativeLayout) findViewById(R.id.rl_open_car);
        llEndurance = (LinearLayout) findViewById(R.id.ll_endurance);
        bottom = (LinearLayout) findViewById(R.id.bottom);
        tvFinishUsing = (TextView) findViewById(R.id.tv_finish_using);
    }

    @Override
    public void ViewTreeObserver() {
        super.ViewTreeObserver();
        CustomHeightBean bean = new CustomHeightBean();
        bean.ExitOffset = layout.getHeight();
        bean.MaxOffset = bottom.getHeight() - tvFinishUsing.getHeight();
        bean.flag = MainActivityInterFace.INTT_STATUS_ONCLICK;
        initRect();
        MyAppcation.getMyAppcation().notifyDataSetChanged(MainActivity.class, Type.A_Main.CHANGE_UI_CODE, bean);
    }

    public void setOffext(int currentProgress){
        if(tvFinishUsing!=null && mRect!=null) {
            tvFinishUsing.layout(mRect.left, -currentProgress + mRect.top, mRect.right, mRect.bottom - currentProgress);
        }
    }

    @Override
    public void initRect() {
        if(mRect==null) {
            int left = tvFinishUsing.getLeft();
            int top = tvFinishUsing.getTop();
            int right = tvFinishUsing.getRight();
            int bottom = tvFinishUsing.getBottom();
            mRect = new Rect(left, top, right, bottom);
        }
    }

    @Override
    public void initData() {

        if (bean != null) {
            tvCarNumber.setText(bean.car_number);
            tvEndurance.setText(bean.getEndurance() + "km");
            tvCarGenreName.setText(bean.car_genre_name);
            tvCarSeat.setText(bean.car_seat + "座");
            if (bean.is_show_send_car_alert == 1) {
                phone.setVisibility(View.VISIBLE);
            } else {
                phone.setVisibility(View.GONE);
            }


            if (task != null) {
                task.setTimeListener(new TimeListener() {

                    @Override
                    public void timeOnTick(long time) {

                        Get_user_order_moneyRequest requestBean = new Get_user_order_moneyRequest();
                        requestBean.order_id = bean.order_id;
                        requestBean.sim = bean.tbox_sim;
                        MyAppcation.getMyAppcation().getPostData(getActivity(), requestBean,
                                new GetDataInterFace<String>() {

                                    @Override
                                    public void onResponse(String response) {

                                        BaseBeanResponse<String> baseBean = JSON.parseObject(response,
                                                new TypeReference<BaseBeanResponse<String>>() {
                                                });
                                        if (baseBean.errCode == 10004) {
                                            task.cancel();
                                        } else if (baseBean.errCode == 0) {
                                            ResponseUserOrderMoney base = JSON.parseObject(baseBean.data,
                                                    ResponseUserOrderMoney.class);
                                            int time = Integer.parseInt(base.orderMoneyInfoArr.car_off_minute_total)
                                                    + Integer.parseInt(base.orderMoneyInfoArr.car_on_minute_total);
                                            int hours = time / 60;
                                            tvPay.setText((hours / 24 == 0 ? "" : (hours / 24 + "天"))
                                                    + (hours % 24 == 0 ? "" : (hours % 24 + "小时")) + time % 60
                                                    + "分钟    " + (base.money) + "元");
                                            bean.is_lock_money = base.orderMoneyInfoArr.is_lock_money;
                                        } else {
                                            task.cancel();

                                        }
                                    }
                                }, null);
                    }

                    @Override
                    public void timeFinish() {
                        task.cancel();
                        task.start();
                    }
                });
                task.start();
            }
        }
    }

    @Override
    public void initEvent() {
        if (bean != null) {
            rlCloseCar.setOnClickListener(this);
            rlOpenCar.setOnClickListener(this);
            rlFindCar.setOnClickListener(this);
            phone.setOnClickListener(this);
            llEndurance.setOnClickListener(this);
            tvFinishUsing.setOnClickListener(this);
        }

    }

    private void get_car_status() {
        Get_car_statusRequest requestBean = new Get_car_statusRequest();
        requestBean.car_id = bean.car_id;
        requestBean.type = 1;
        promptDialog.show();
        MyAppcation.getMyAppcation().getPostData(getActivity(), requestBean, new GetDataInterFace<String>() {

            @Override
            public void onResponse(String response) {
                promptDialog.dismiss();
                ResponseCarStatus bean = JSON.parseObject(response, ResponseCarStatus.class);
                tvEndurance.setText(bean.getEndurance() + "km");
            }
        }, new DisssmissInterFace() {

            @Override
            public void putError(VolleyError error) {
                promptDialog.dismiss();
            }
        });
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.ll_endurance:
                get_car_status();
                break;
            case R.id.phone:

                SongChePhoneTipDialog songChePhoneTipDialog = new SongChePhoneTipDialog(getActivity(),
                        bean.send_car_service_time, bean.send_car_service_money, bean.send_car_service_tel);
                songChePhoneTipDialog.show();
                songChePhoneTipDialog.setOnSongChePhoneTipDialog(new SongChePhoneTipDialog.OnSongChePhoneTipDialog() {

                    @Override
                    public void quxiao() {

                    }

                    @Override
                    public void phone() {

                    }
                });
                break;

            case R.id.tv_finish_using:
                Intent intent = new Intent(MyAppcation.getMyAppcation(), ShortTimeOrderPayActivity.class);
                intent.putExtra("bean", bean);
                startActivityForResult(intent, CodeConstant.HCActivity);
                break;
            case R.id.rl_find_car:
                if (isSearch) {
                    isSearch = false;
                    seek_carRequest();
                } else {
                    Tools.showMessage("操作频繁，稍后重试");
                }

                break;
            case R.id.rl_close_car:

                if (isOperateCar) {
                    isOperateCar = false;
                    type = 0;
                    operateCar();
                } else {
                    Tools.showMessage("操作频繁，稍后重试");
                }

                break;

            case R.id.rl_open_car:
                if (isOperateCar) {
                    isOperateCar = false;
                    type = 1;
                    operateCar();
                } else {
                    Tools.showMessage("操作频繁，稍后重试");
                }

                break;


            default:
                break;
        }
    }

    private void seek_carRequest() {
        Seek_carRequest requestBean = new Seek_carRequest();
        requestBean.car_id = bean.car_id;
        requestBean.type = SeekCarCode.TYPE;
        promptDialog.show();
        MyAppcation.getMyAppcation().getPostData(getActivity(), requestBean, new GetDataInterFace<String>() {

            @Override
            public void onResponse(String response) {

                promptDialog.dismiss();
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        isSearch = true;
                    }
                }, 5000);
                Seek_carResponse bean = JSON.parseObject(response, Seek_carResponse.class);
                bean.type = 0;
                MyAppcation.getMyAppcation().notifyDataSetChanged(MainActivity.class, Type.A_Main.SEARCH_CAR_CODE,
                        bean);

            }
        }, new DisssmissInterFace() {

            @Override
            public void putError(VolleyError error) {
                promptDialog.dismiss();
                isSearch = true;
                Tools.showMessage("操作失败");
            }
        });

    }

    /**
     * 开关车门寻车
     */
    private void operateCar() {

        Handle_car_doorRequest requestBean = new Handle_car_doorRequest();
        requestBean.car_id = bean.car_id;
        requestBean.type = type;
        promptDialog.show();
        MyAppcation.getMyAppcation().getPostData(getActivity(), requestBean, new GetDataInterFace<String>() {

            @Override
            public void onResponse(String response) {

                promptDialog.dismiss();
                try {
                    new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            switch (type) {
                                case 0:
                                case 1:
                                    isOperateCar = true;
                                    break;
                                case 2:
                                    isSearch = true;
                                    break;
                                default:
                                    break;
                            }

                        }
                    }, 5000);
                    if (response.equals("true")) {
                        switch (type) {
                            case 0:
                                Tools.showMessage("关门成功");
                                break;
                            case 1:
                                Tools.showMessage("开门成功");
                                break;
                            case 2:
                                Tools.showMessage("操作成功");
                                break;
                            default:
                                break;
                        }
                    } else {
                        Tools.showMessage("操作失败");
                    }
                } catch (Exception e) {
                    Tools.showMessage("操作失败");
                }
            }
        }, new DisssmissInterFace() {

            @Override
            public void putError(VolleyError error) {

                switch (type) {
                    case 0:
                        isOperateCar = true;
                        Tools.showMessage("关门失败");
                        break;
                    case 1:
                        isOperateCar = true;
                        Tools.showMessage("开门失败");
                        break;
                    case 2:
                        isSearch = true;
                        Tools.showMessage("操作失败");
                        break;
                    default:
                        break;
                }
                promptDialog.dismiss();
            }
        });
    }


}
